import { useState, forwardRef, useImperativeHandle } from 'react'
import { Button, Input, MessagePlugin, Radio, RadioGroup } from 'tdesign-react'
import { useTranslation } from 'react-i18next'
import '../index.less'

const CreateQuestionnaireQuestions = forwardRef((props: any, ref: any) => {
  const { questionFlag, questionList, setQuestionFlag, setQuestionList } = props
  const { t } = useTranslation(['webGames'])

  useImperativeHandle(ref, () => ({ getQuestionData, questionTypeList }))

  const questionTypeList = ['radio','checkbox','input']

  // 填写题目标题
  const onQuestionTitleChange = (event: string) => {
    let _questionList = [...questionList]
    _questionList[questionFlag].title = event
    setQuestionList(_questionList)
    console.log('_questionList', _questionList)
  }

  // 选择题目类型
  const onQuestionTypeChange = (event: any) => {
    let _questionList = [...questionList]
    if (!_questionList[questionFlag].type) {
      _questionList[questionFlag].optionList.push({ label: '', value: '' })
    }
    _questionList[questionFlag].type = event
    setQuestionList(_questionList)
  }

  //选项
  const onOptionChange = (event: string, index: number, optionKey: 'label' | 'value') => {
    let _questionList = [...questionList]
    let _optionsList = [..._questionList[questionFlag].optionList]
    _optionsList[index][optionKey] = event
    _questionList[questionFlag].optionList = _optionsList
    setQuestionList(_questionList)
  }


  //添加选项 (1.把没有填写value值的补充完整，2.检查label、value是否合法（也就是label是否为空和value是否重复）)
  const addOptionItem = () => {
    let _optionsList = [...questionList[questionFlag].optionList]
    /** 只需要判断label有没有空的，value有没有重复的，其中空value我们还要给他补全 */
    let _labelList: string[] = [], _valueList: string[] = []
    _optionsList.forEach((item: OptionType, index: number) => {
      _labelList.push(item.label)
      _valueList.push(item.value || item.label)
      _optionsList[index].value = _optionsList[index].value || _optionsList[index].label
    })
    let labelHasEmpty = false, valueHasDuplicate = false
    // 拿到数据之后再遍历一下label 有没有空的，同时也可以判断一下 value 有没有重复的
    for (let index = 0; index < _labelList.length; index++) {
      if (!_labelList[index]) {
        labelHasEmpty = true
        break
      }
    }
    if (_valueList.length !== (new Set(_valueList)).size) {
      valueHasDuplicate = true
    }
    if (!labelHasEmpty && !valueHasDuplicate) {
      _optionsList.push({ label: '', value: '' })
    }
    let _questionList = [...questionList]
    _questionList[questionFlag].optionList = _optionsList
    setQuestionList(_questionList)
    if (labelHasEmpty) {
      MessagePlugin.error({
        content: '你还没填写完成所有的选项',
        placement: 'top-right',
        duration: 2000
      })
      return
    }
    if (valueHasDuplicate) {
      MessagePlugin.error({
        content: '选项值有重复的，请检查',
        placement: 'top-right',
        duration: 2000
      })
      return
    }
  }

  const getQuestionData = () => {
    return '我被父组件调用了'
  }

  return <div className='create-single-question'>
      <Input
        className='input-question-title'
        label={t('questionnaires.questionNameLabel')}
        placeholder={t('questionnaires.questionNameLabel')}
        key={`${questionFlag}-question-title`}
        defaultValue={questionList[questionFlag].title}
        onChange={onQuestionTitleChange}
      />
      <div className='question-type-select'>
        <span className='question-type-label'>{t('questionnaires.questionTypeLabel')}</span>
        <RadioGroup onChange={onQuestionTypeChange} key={`${questionFlag}-question-type`} defaultValue={questionList[questionFlag].type}>
          {questionTypeList.map((item: string, index: number) => {
            return <Radio value={item} key={item}>{t(`questionnaires.${item}`)}</Radio>
          })}
        </RadioGroup>
      </div>
      { (questionList[questionFlag].type == 'radio' || questionList[questionFlag].type == 'checkbox') && <div className='add-select-options' key={`${questionFlag}-question-options`}>
          {questionList[questionFlag].optionList.map((item: any, index: number) => {
            return <div className='radio-option' key={index}>
              <span className='radio-option-title'>选项{index + 1}</span>
              <Input
                className='radio-option-label'
                placeholder='请输入要显示的选项名称'
                key={`${questionList[questionFlag].type}-${index}-option-label`}
                value={item.label}
                onChange={(event) => { onOptionChange(event, index, 'label') }}
              />
              <Input
                className='radio-option-value'
                placeholder='请输入选项对应的值（留空表示与名称一致）'
                key={`${questionList[questionFlag].type}-${index}-option-value`}
                value={item.value}
                onChange={(event) => { onOptionChange(event, index, 'value') }}
              />
            </div>
          })}
          <Button onClick={addOptionItem}>{questionList[questionFlag].type == 'radio' ? '添加单选选项' : '添加多选选项'}</Button>
      </div>}
    </div>
})
export default CreateQuestionnaireQuestions
